package com.xixi.demo.controller;

import com.xixi.demo.model.BlogInfo;
import com.xixi.demo.model.PageRequest;
import com.xixi.demo.model.PageResult;
import com.xixi.demo.model.Result;
import com.xixi.demo.service.BlogService;
import com.xixi.demo.utils.JWTUtils;
import io.jsonwebtoken.lang.Assert;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @RequestMapping("/getList")
    public PageResult<BlogInfo> selectAll(PageRequest pageRequest){
        log.info("接收到参数:{}", pageRequest.getCurrentPage());
        return blogService.getBookListByPage(pageRequest);
    }
    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId, HttpServletRequest request){
        Assert.notNull(blogId, "blogId不能为null");

        BlogInfo blogInfo = blogService.getBlogDetail(blogId);
        Integer authorId = blogInfo.getUserId();
        String userToken = request.getHeader("user_token_header");
        Integer userId = JWTUtils.getUserIdFromToken(userToken);
        if(authorId != null && authorId == userId){
            blogInfo.setIsLoginUser(true);
        }
        return blogInfo;
    }

    @RequestMapping("/addBlog")
    public Result<Boolean> addBlog(@RequestBody BlogInfo blogInfo, HttpServletRequest request){
        log.info("addBlog接收到参数title: {}", blogInfo.getTitle());
        if(blogInfo.getTitle().equals("")){
            return Result.noTitle();
        }
        if(blogInfo.getContent().equals("")){
            return Result.noContent();
        }
        String userToken = request.getHeader("user_token_header");
        Integer userId = JWTUtils.getUserIdFromToken(userToken);
        blogInfo.setUserId(userId);
        log.info("userId:{}", blogInfo.getUserId());
        Integer result = null;
        try {
            result = blogService.addBlog(blogInfo);
            if(result == 1){
                return Result.success(true);
            }
        }catch (Exception e){
            log.error("发布博客失败: e", e);
        }
        return Result.fail("发布失败");
    }
    @RequestMapping("/update")
    public Integer updateBlog(@RequestBody BlogInfo blogInfo){
        log.info("id:{}",blogInfo.getId());
        return blogService.updateBlog(blogInfo);
    }
    @RequestMapping("delete")
    public Integer deleteBlog(Integer blogId){
        return blogService.deleteBlog(blogId);
    }
}
